package img

import (
	"fmt"
	"gocv.io/x/gocv"
	"image/color"
	"log"
	"math"
)

// 将像素点数组转换为灰度图像
func createGrayImageFromPixels(pixels [][]uint8, width, height int) *gocv.Mat {
	img := gocv.NewMatWithSize(height, width, gocv.MatTypeCV8UC1)
	for y := 0; y < height; y++ {
		for x := 0; x < width; x++ {
			img.SetUCharAt(y, x, pixels[y][x])
		}
	}
	return &img
}

// 计算互相关系数
func calculateCrossCorrelationCoefficient(img1, img2 *gocv.Mat) float64 {
	rows, cols := img1.Rows(), img1.Cols()
	totalPixels := float64(rows * cols)

	// 计算每个图像的均值
	mean1 := 0.0
	mean2 := 0.0
	for y := 0; y < rows; y++ {
		for x := 0; x < cols; x++ {
			p1 := float64(img1.GetUCharAt(y, x))
			p2 := float64(img2.GetUCharAt(y, x))
			mean1 += p1
			mean2 += p2
		}
	}
	mean1 /= totalPixels
	mean2 /= totalPixels

	// 计算协方差和标准差
	covariance := 0.0
	stdDev1 := 0.0
	stdDev2 := 0.0
	for y := 0; y < rows; y++ {
		for x := 0; x < cols; x++ {
			p1 := float64(img1.GetUCharAt(y, x))
			p2 := float64(img2.GetUCharAt(y, x))
			diff1 := p1 - mean1
			diff2 := p2 - mean2
			covariance += diff1 * diff2
			stdDev1 += diff1 * diff1
			stdDev2 += diff2 * diff2
		}
	}
	covariance /= totalPixels
	stdDev1 = math.Sqrt(stdDev1 / totalPixels)
	stdDev2 = math.Sqrt(stdDev2 / totalPixels)

	// 计算互相关系数
	if stdDev1 == 0 || stdDev2 == 0 {
		return 0.0
	}
	corrCoeff := covariance / (stdDev1 * stdDev2)
	return corrCoeff
}

func BFMatcher(img1, img2 gocv.Mat) {
	// 创建特征检测器和描述符
	featureDetector := gocv.NewORB()
	defer featureDetector.Close()

	// 提取特征点和描述符
	keypoints1, descriptors1 := featureDetector.DetectAndCompute(img1, gocv.NewMat())
	keypoints2, descriptors2 := featureDetector.DetectAndCompute(img2, gocv.NewMat())

	if len(keypoints1) == 0 || len(keypoints2) == 0 {
		log.Fatal("没有检测到特征点")
	}

	// 创建匹配器
	matcher := gocv.NewBFMatcher()
	err := matcher.Close()
	if err != nil {
		return
	}

	// 进行特征点匹配
	matches := matcher.Match(descriptors1, descriptors2)

	// 绘制匹配结果
	imgResult := gocv.NewMat()
	gocv.DrawMatches(img1, keypoints1, img2, keypoints2, matches, &imgResult,
		color.RGBA{255, 0, 0, 255},
		color.RGBA{0, 255, 0, 255}, nil, gocv.DrawDefault)

	// 保存匹配结果
	gocv.IMWrite("matches.jpg", imgResult)

	fmt.Println("匹配结果保存成功")
}
